/*
 * @Author: wuxiangyi
 * @Date: 2023-06-02 19:22:25
 * @LastEditors: wuxiangyi
 * @LastEditTime: 2023-06-02 21:54:57
 * @FilePath: /RSSHub/lib/routes/juejin/article.js
 * @Description:
 *
 */
const got = require('@/utils/got');
const cheerio = require('cheerio');

// 基础信息查询接口
const baseApi = 'https://api.juejin.cn/search_api/v1/search';
const uiApi = 'https://juejin.cn/post';

module.exports = async (ctx) => {
    const content = ctx.params.content;
    const query_data = {
        aid: '2608',
        uuid: '7065537302294775309',
        spider: 0,
        query: content,
        id_type: 0,
        cursor: 0,
        limit: 20,
        search_type: 0,
        sort_type: 0,
        version: 1
    };
    const response = await got(baseApi, {
        searchParams: {
            ...query_data
        }
    });
    // 用 cheerio 来把请求回来的数据转成 DOM，方便操作
    const article_list = response.data.data;
    const out = await Promise.all(
        article_list.map(async (item) => {
            const uiUrl = uiApi + '/' + item.result_model.article_id;
            // 这里是使用 RSSHub 的缓存机制
            const cache = await ctx.cache.get(uiUrl);
            if (cache) {
                return Promise.resolve(JSON.parse(cache));
            }
            const uiResp = await got(uiUrl);
            const $ = cheerio.load(uiResp.body);
            const single = {
                title: $('title').text(),
                link: uiUrl,
                description: $('.markdown-body').html().trim(),
                pubDate: new Date(item.result_model.article_info.ctime * 1000).toUTCString(),
            };
            ctx.cache.set(uiUrl, JSON.stringify(single), 24 * 60 * 60);
            return Promise.resolve(single);
        })
    );
    // 最后设置一下 RSS 链接里面包含的内容，item 就是输出的各个文章项
    ctx.state.data = {
        title: '掘金 - ' + content,
        baseApi,
        description: '掘金 - ' + content + ' 最新抓取',
        item: out,
    };
};
